//同时发布多条会导致禁言，目前合成一条发送

const puppeteer = require('puppeteer')
const axios = require('axios')
const { uniFriendUrl, searchUrl } = require('./utils/enum')
const dayjs = require('dayjs')
const fs = require('fs')
const path = require('path')

const { getHtmlWithPuppeteer } = require('./utils')
const { parseTimePlace, isAddFn, addTimeGround, uploadImg, parseFileID, updateFriend } = require('./utils/method')
async function openChrome() {
    //公司笔记本地址
    // const  executablePath= 'C:/Users/wangyongjie/AppData/Local/Google/Chrome/Application/chrome'

    //家里和公司台式地址
    // const executablePath = 'C:/Program Files/Google/Chrome/Application/chrome'

    // const browser = await puppeteer.launch({
    //     headless: 'new',
    //     executablePath,
    // })
    /**
     * 自动获取geogle地址
     * */
    // const browser = await puppeteer.launch({
    //     headless: 'new',
    // })

    /**
     * 启动调试
     * */
    const userDataDir = path.resolve(__dirname, 'user-data')

    const browser = await puppeteer.launch({
        userDataDir,
        headless: false,
        // executablePath,
        args: ['--auto-open-devtools-for-tabs'], // 自动打开调试窗口
    })
    const page = await browser.newPage()

    await page.setDefaultNavigationTimeout(120 * 1000)

    // 设置视口大小，避免显示不全时，某些元素延迟加载，导致无法获取
    await page.setViewport({
        width: 1020,
        height: 880,
    })
    return { page, browser }
}

async function xhsShare({ nameArr, page }) {
    const url = 'https://creator.xiaohongshu.com/publish/publish'
    let result = true
    const localImgArr = []

    try {
        // 访问页面
        await page.goto(url, { waitUntil: 'networkidle2' })
        const imgButtonSelector = 'div.header > div:nth-child(2)'
        const imgSelectSelector =
            'div.upload-container > div.video-uploader-container.upload-area > div.upload-wrapper > div > input'
        const topicSelector = '#tributeContainer > div > ul > li.publish-topic-item.publish-highlight'
        // 等待页面加载完成
        await page.waitForSelector(imgButtonSelector) // 这里选择了一个按钮，你可以根据实际情况修改选择器

        // 1.切换为上传图文
        await page.click(imgButtonSelector)

        // 2.上传图片
        const input = await page.$(imgSelectSelector)
        const imgArr = nameArr.map((item) => item.img)
        for (let i = 0; i < Math.min(imgArr.length, 18); i++) {
            const imageUrl = imgArr[i]

            if (!imageUrl) continue
            // 下载网络图片到本地
            const response = await axios({
                url: imageUrl,
                method: 'GET',
                responseType: 'stream',
            })
            const localImagePath = './user-data/start-img/' + dayjs().valueOf() + '.jpg' // 保存到本地的路径

            response.data.pipe(fs.createWriteStream(localImagePath))
            // 等待图片下载完成
            await new Promise((resolve) => {
                response.data.on('end', resolve)
            })
            localImgArr.push(localImagePath)
        }

        await page.evaluate((imgSelectSelector) => {
            const fileInput = document.querySelector(imgSelectSelector)
            fileInput.addEventListener('change', () => {
                window.onFileUploadComplete()
            })
        }, imgSelectSelector)

        await input.uploadFile(...localImgArr) // 上传本地图片文件

        // 等待文件上传完成的标志，这里使用了页面上的一个元素的出现作为标志
        await page.waitForSelector('.upload-complete', { timeout: 1200 * 1000 })

        //3.输入标题
        const titleInputSelector = 'div.content > div.c-input.titleInput > input'
        const inputTitle = await page.$(titleInputSelector)
        await inputTitle.type(`${dayjs().format('YYYY-MM-DD')}，今日${nameArr.length}位明星生日`)
        await page.waitForTimeout(1000)

        //4.点击话题按钮
        for (let i = 0; i < nameArr.length; i++) {
            const { name, time } = nameArr[i]
            await page.click('#topicBtn')
            await page.waitForTimeout(2000)
            // 模拟用户使用键盘输入内容，唤起话题列
            await page.keyboard.type(name)
            await page.waitForTimeout(2000)
            //5.点击第一个话题
            if (await page.$(topicSelector)) {
                page.click(topicSelector)
            }
            await page.waitForTimeout(1000)

            await page.keyboard.type(`${dayjs(time).format('YYYY-MM-DD')}——${dayjs().diff(time, 'year')}岁生日！`)
            await page.keyboard.press('Enter')

            await page.waitForTimeout(2000)
        }
        await page.keyboard.type(
            `距清明节4月4日还有${dayjs('2024-04-04').diff(dayjs(), 'day')}天，是时光丫，记录美好生活！`,
        )
        await page.waitForTimeout(1000)

        // await page.evaluate(function () {
        //     let dom = document.querySelector('#post-textarea')
        //     const innerHtml = dom.innerHTML
        //     dom.innerHTML = innerHtml + '前往微信小程序《' + '<a>是时光丫</a>' + '》，查看更多明星生日<br />'
        // })
        // //6.点击发布按钮
        const submitSelector =
            'div.img-post > div.content > div.submit > button.css-k3hpu2.css-osq2ks.dyn.publishBtn.red'
        await page.waitForSelector(submitSelector)
        page.click(submitSelector)
        await page.waitForTimeout(2000)
    } catch (e) {
        result = false
        console.log(e)
    }

    return { result, localImgArr }
}

async function wbShare({ localImgArr, nameArr, page }) {
    const url = 'https://weibo.com'

    let result = true
    try {
        // 访问页面
        await page.goto(url, { waitUntil: 'networkidle2' })
        const imgSelectSelector =
            '#homeWrap > div.woo-panel-main.woo-panel-top.woo-panel-right.woo-panel-bottom.woo-panel-left > div > div.grayTheme > div > div > div > div > div > input'

        const topicSelector =
            '#homeWrap > div.woo-panel-main.woo-panel-top.woo-panel-right.woo-panel-bottom.woo-panel-left > div > div > div > div.woo-box-flex.woo-box-column > div.woo-box-item-flex > div > div.woo-box-item-flex'
        // 等待页面加载完成

        // 1.上传图片
        const input = await page.$(imgSelectSelector)

        await page.evaluate((imgSelectSelector) => {
            const fileInput = document.querySelector(imgSelectSelector)
            fileInput.addEventListener('change', () => {
                window.onFileUploadComplete()
            })
        }, imgSelectSelector)

        await input.uploadFile(...localImgArr) // 上传本地图片文件

        // 等待文件上传完成的标志，这里使用了页面上的一个元素的出现作为标志
        await page.waitForSelector('.upload-complete', { timeout: 120 * 1000 })

        //2.点击话题按钮前，清空微博缓存内容

        await page.click(
            '#homeWrap > div.woo-panel-main.woo-panel-top.woo-panel-right.woo-panel-bottom.woo-panel-left > div > div:nth-child(4) > div > div.woo-box-item-flex > div > div:nth-child(4) > div',
        )

        const textareaSelector =
            '#homeWrap > div.woo-panel-main.woo-panel-top.woo-panel-right.woo-panel-bottom.woo-panel-left > div > div > div > textarea'

        await page.evaluate(function (textareaSelector) {
            let dom = document.querySelector(textareaSelector)
            dom.value = ''
            localStorage.removeItem('from_content')
        }, textareaSelector)

        // 模拟用户使用键盘输入内容，唤起话题列

        for (let i = 0; i < nameArr.length; i++) {
            const { name, time } = nameArr[i]
            await page.keyboard.type('#' + name)
            await page.keyboard.press('Space')
            await page.waitForTimeout(1000)
            await page.keyboard.press('Backspace')
            await page.waitForTimeout(2000)
            //3.点击第一个话题
            if (await page.$(topicSelector)) {
                page.click(topicSelector)
            }
            await page.waitForTimeout(1000)
            await page.keyboard.type(`${dayjs(time).format('YYYY-MM-DD')}——${dayjs().diff(time, 'year')}岁生日！`)
            await page.keyboard.press('Enter')
            await page.waitForTimeout(2000)
        }
        await page.keyboard.type(
            `距春节2月10日还有${dayjs('2024-02-10').diff(dayjs(), 'day')}天，是时光丫，记录美好生活`,
        )
        await page.waitForTimeout(1000)

        //6.点击发布按钮
        const submitSelector =
            '#homeWrap > div.woo-panel-main.woo-panel-top.woo-panel-right.woo-panel-bottom.woo-panel-left > div > div:nth-child(4) > div > div > button'
        await page.waitForSelector(submitSelector)
        page.click(submitSelector)
        await page.waitForTimeout(2000)
    } catch (e) {
        result = false
        console.log(e)
    }

    return result
}

async function getBirthdayList() {
    let result = []
    try {
        let res = await axios({
            method: 'post',
            url: uniFriendUrl.currentBirthdayList,
        })
        if (res.data.code == 200) {
            result = res.data.data
        }
    } catch (e) {
        console.log(e)
    }
    return result
}

async function updateImage({ name, lemmaId, _id }) {
    let poster = []
    try {
        const lemmaTitle = name
        const { coverUrl, baseInfo, posterUrlArr } = await getHtmlWithPuppeteer(`${searchUrl}/${lemmaTitle}/${lemmaId}`)

        poster = await addTimeGround({
            lemmaId,
            lemmaTitle,
            coverUrl,
            posterUrlArr,
            baseInfo,
            _id,
        })
    } catch (error) {
        console.error('获取页面内容时出错:', error.message)
    }
    return poster
}

let num = 0 //记录main运行次数
async function main(needSend = []) {
    if (num > 5) return
    num++
    const birthdayList = await getBirthdayList()
    const nameArr = []

    for (let i = 0; i < birthdayList.length; i++) {
        let { time, name, _id, lemmaId, poster, posterUpdated } = birthdayList[i]
        if (!posterUpdated) {
            const newPoster = await updateImage({ name, _id, lemmaId })
            if (newPoster.length > 0) {
                poster = newPoster
            }
        }
        nameArr.push({ name, time, img: poster.map((item) => item.url)[0] })
    }

    const { page, browser } = await openChrome()

    // 监听文件上传完成事件
    // 挂载到页面的方法在多次跳转后扔有用  Functions installed via page.exposeFunction survive navigations
    await page.exposeFunction('onFileUploadComplete', () => {
        console.log('File upload complete!')
        // 这里可以添加你的文件上传完成后的逻辑
        page.evaluate(() => {
            const completeDom = document.createElement('div')
            completeDom.classList = 'upload-complete'
            document.body.append(completeDom)
        })
    })

    const { result: xhsShareRes, localImgArr } = await xhsShare({ nameArr, page })

    if (xhsShareRes) {
        const wbShareRes = await wbShare({ nameArr, localImgArr, page })
        await browser.close()
    }

    // 关闭浏览器
}

main()
// openChrome() //新电脑先执行该方法打开浏览器，在浏览器中登录小红书和微博账号
